
function easemobMQTT(options= []) {
    this.init(options);
}


easemobMQTT.prototype = {
	debug: true, // 调试信息显示
	authConfig: {
		// REST API 访问地址 https://console.easemob.com/app/im-service/detail 
		baseUrl	: 'a1.easemob.com', 
		// APPKEY https://console.easemob.com/app/applicationOverview/detail 
		orgName : '1113181124010841', 
		// APPKEY https://console.easemob.com/app/applicationOverview/detail 
		appName : 'cloudstudio',	
		// CLIENT ID https://console.easemob.com/app/applicationOverview/detail 
		clientId: 'YXA6KMsxsO--EeiNQJmhf8gr3w',
		// CLINET SECRET  https://console.easemob.com/app/applicationOverview/detail 
		clientSecret: 'YXA6FBHoX7zcDwmO49D6PB7AbB3TjqY',

    },

    /** 连接配置 */
    connectConfig:{
    	//  连接地址 https://console.easemob.com/app/generalizeMsg/overviewService
    	host : 'rmwzi0.cn1.mqtt.chat', 
	    // WebSocket 协议服务端口，如果是走 HTTPS，设置443端口
	    port: 443 , 	
	    // APPID  https://console.easemob.com/app/generalizeMsg/overviewService 
	    appId: 'rmwzi0',  
	    //  用户自定义deviceID
	    deviceId :'deviceId',
	    // clientId 格式 deviceID@AppID
	    clientId : 'deviceId@rmwzi0', //

    	// 是否走加密 HTTPS，如果走 HTTPS，设置为 true
    	useTLS : true, 
    	// cleansession标志
    	cleanSession : true, 
    	// 超时重连时间
    	reconnectTimeout : 2000, 
    	// 请求超时时间
    	timeout: 2, 
        // mqtt版本号
        mqttVersion: 4, 
    },
    /** 初始化客户端 */
    init:function (options) {
    	_this = this;
		Object.keys(options).forEach((key) => {
	        this[key] = options[key];
	    });

        // 初始化客户端
        this.mqtt = new Paho.MQTT.Client(
            this.connectConfig.host,
            this.connectConfig.port,
            this.connectConfig.clientId
        );

        this.mqtt.onMessageArrived = function(message){
        	_this.onMessageArrived(message);
        }
        this.mqtt.onConnectionLost  = function(message){
        	_this.onConnectionLost(message);
        }
        this.mqtt.onMessageDelivered  = function(message){
        	_this.onMessageDelivered(message);
        }
    },

    /** 获取管理员token */
    getAccessToken:function(username,password){
    	_this = this;
    	var urlArray = [
	    	this.authConfig.baseUrl,
	    	this.authConfig.orgName,
	    	this.authConfig.appName,
	        'token'
	    ];

	    var params = {
	        "grant_type":'client_credentials',
	        "client_id": this.authConfig.clientId,
	        "client_secret": this.authConfig.clientSecret
	    };

	    var result = false;
	    $.ajax({
	        url:'http://'+urlArray.join('/'),
	        data:JSON.stringify(params),
	        type:'post',
	        dataType:'json',
	        async:false,
	        success:function (response) {
	        	result = true
	            _this.debugMessage('accessToken获取成功');
	            _this.debugMessage(response);
	            _this.accessToken = response.access_token;
	            // 
	        },
	        error:function (response) {
	            _this.debugMessage('accessToken获取失败');
	            _this.accessToken = '';
	            result = false;
	        }
	    });
	    return result;
    },

    register:function(username,password){
    	var _this = this;
    	// 注册用户
    	var urlArray = [
	    	this.authConfig.baseUrl,
	    	this.authConfig.orgName,
	    	this.authConfig.appName,
	        'users'
	    ];
	    var params = [
	        	{
	        		"password": password,
	        		"username": username
	        	}
	        ];
	    var result = false;
	    $.ajax({
	        url:'http://'+urlArray.join('/'),
	        data:JSON.stringify(params),
	        type:'post',
	        dataType:'json',
            headers: {
		        Authorization: "Bearer "+_this.accessToken
		    },
	        async:false,
	        success:function (response) {
	            _this.debugMessage('用户注册成功');
	            _this.debugMessage(response);
	            result = true;
	        },
	        error:function (response) {
	            _this.debugMessage('用户注册失败');
	             _this.debugMessage(response);
	            result = false;
	        }
	    });
	    return result;
    },
    /** 获取用户凭证 */
    login:function (username,password){
    	_this = this;
    	var urlArray = [
	    	this.authConfig.baseUrl,
	    	this.authConfig.orgName,
	    	this.authConfig.appName,
	        'token'
	    ];

	    var params = {
	        "grant_type":'password',
	        "password": password,
	        "username": username
	    };

	    $.ajax({
	        url:'http://'+urlArray.join('/'),
	        data:JSON.stringify(params),
	        type:'post',
	        dataType:'json',
	        async:false,
	        success:function (response) {
	            _this.debugMessage('用户登陆成功');
	            token = response.access_token;
	            result = true;
	        },
	        error:function (response) {
	        	_this.debugMessage(response);
	            _this.debugMessage('用户登陆失败');
	            token = '';
	            result = false;
	        }
	    });
	    this.username = username;
    	this.password = password;
	    this.token = token;
	    return result;
    },


    /** 连接服务器 */
    connect:function(){
    	_this = this;
    	var options = {
	        timeout : this.connectConfig.mqttVersion,
	        mqttVersion : this.connectConfig.mqttVersion,
	        cleanSession : this.connectConfig.cleanSession,
	        useSSL : this.connectConfig.useTLS,
	        userName : this.username, 
	        password : this.token,

	        onSuccess: function(message){
	        	_this.onConnectionSuccess(message);
	        },
	        onFailure: function (message) {
	            // 连接失败回调
	            _this.onConnectionFailure(message);
	           
	        }
	    }
    	this.mqtt.connect(options);
    },
    /** 订阅 */
    subscribe:function(topic){
    	// 订阅消息 QoS参数代表传输质量，可选0，1，2。详细信息，请参见名词解释。
    	if(this.mqtt.isConnected()){
    		this.mqtt.subscribe(topic, { qos: 1 });
	    	this.debugMessage('订阅成功'+topic);
    	}else{
    		this.debugMessage('mqtt状态异常,订阅失败')
    	}
	    
    },
    /** 取消订阅 */
    unsubscribe:function(topic){
    	this.mqtt.unsubscribe(topic)
    	this.debugMessage('取消订阅成功');
    },
    /** 消息发送 */
    sendMessage:function(topic,message){
		message = new Paho.MQTT.Message(message)
		message.destinationName = topic
		this.mqtt.send(message);
		this.debugMessage('消息发送成功');
	},
	/** 中断连接 */
	discounnect:function(){
		this.mqtt.disconnect();
		this.debugMessage('连接中断');
	},

	/**  获取当前连接状态 */
	isConnect:function(){
		if(this.mqtt.isConnected()==true){
			return true;
		}else{
			return false;
		}
	},

	// ------------------------------------------方法回调---------------------------------------
	// 
	/** 连接成功 */
	onConnectionSuccess:function(){
		this.debugMessage('服务器连接成功');    
	},
	/** 连接失败 */
	onConnectionFailure:function(){
		this.debugMessage('服务器连接失败');
        setTimeout(this.connect, this.connectConfig.reconnectTimeout);
	},
	/** 连接丢失 */
	onConnectionLost:function(message){
		this.debugMessage('连接已丢失');
		setTimeout(this.connect, this.connectConfig.reconnectTimeout);
	},
	/** 消息收达 */
	onMessageArrived:function(message){
        this.debugMessage(message);
        var topic = message.destinationName
        var payload = message.payloadString
        this.debugMessage("接收消息成功: " + topic + "   " + payload)
	},
	/** 消息送达 */
	onMessageDelivered:function(message){
		this.debugMessage('送达消息成功');
	},
	debugMessage:function(message){
		if(this.debug == true){
			console.log(message);
		}
	}
}









